const { getAll,getAllpermRoles,savePermRoles,getopsByPermID,updateOpByID,delOprationByID} = require('../db/permission')
const { result } =require('../config/result')

class PermConntroller{
  async delOprationByID(ctx){
    try{
      const {id} = ctx.request.body
      const ret =  await delOprationByID(id) 
      result.success = true
      result.message = "删除成功"
      result.data = ret
      ctx.body = result 
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
  }
  async updateOpByID(ctx){
    try{
      //const {id,flag} = ctx.request.body
      const ret =  await updateOpByID(ctx.request.body) 
      result.success = true
      result.message = "更新成功"
      result.data = ret
      ctx.body = result 
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
  }

  async getopsByPermID(ctx){
    try{
      const {id,flag} = ctx.request.body
      const ret =  await getopsByPermID(id,flag) 
      result.success = true
      result.message = "获取操作列表成功"
      result.data = ret
      ctx.body = result 
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
  }

  async addpermRoles(ctx)
  {
    try{
      const id= await savePermRoles(ctx.request.body)
      result.success = true
      result.message = "保存成功"
      result.data = id
      ctx.body = result
    }catch(e){
        result.data = '保存失败'
        result.message = e.message
        result.success = false
        ctx.body = result
        ctx.app.emit('error',e.message,ctx)  
    }  
  }
  async getPermRoles(ctx){
    try{
      const ret =  await getAllpermRoles() 
      if(ret && ret.length>0){
        result.success = true
        result.message = "获取权限角色列表成功"
        result.data = ret
        ctx.body = result
      }
      else{
        result.data = null
        result.message = '获取权限角色列表成功'
        result.success = true
        //ctx.app.emit('error','获取权限列表失败',ctx)  
        return
      }  
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
  }  
  }

  async getPerms(ctx){
    try{
      const ret =  await getAll() 
      if(ret && ret.length>0){
        result.success = true
        result.message = "获取权限列表成功"
        result.data = ret
        ctx.body = result
      }
      else{
        result.data = null
        result.message = '获取权限列表成功'
        result.success = true
        //ctx.app.emit('error','获取权限列表失败',ctx)  
        return
      }  
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
      
  }
}

module.exports= new PermConntroller()